package com.qfedu.demo.shiro.realm;

import com.qfedu.demo.shiro.controller.MainController;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 提供认证和授权数据
 */
public class UserRealm extends AuthorizingRealm {

    private final static Logger LOG = LoggerFactory.getLogger(UserRealm.class);

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取用户信息，如果认证时设置的是自定义用户对象，则此处也是自定义对象
        String user = (String)principals.getPrimaryPrincipal();
        LOG.info("doGetAuthorizationInfo - " + user);
        // 构造授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 管理员具有三个权限
        if ("admin".equals(user)) {
            info.addRole("admin");
            info.addStringPermission("user:view");
            info.addStringPermission("role:view");
            info.addStringPermission("menu:view");
            return info;
        }
        // 其他用户具有一个权限
        info.addRole("guest");
        info.addStringPermission("user:view");
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        String user = t.getUsername();
        LOG.info("doGetAuthenticationInfo - " + user);
        String pwd = new String (t.getPassword());
        if (!("admin".equals(user) || "cai".equals(user))) {
            throw new UnknownAccountException();
        }
        if (!"123".equals(pwd)) {
            throw new IncorrectCredentialsException();
        }
        // 构造认证信息，第一个参数为放在session中的对象
        return new SimpleAuthenticationInfo(user, pwd, "myUserRealm");
    }
}
